<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>文件夹文件批量重命名工具</title>
    <link rel="stylesheet" href="/static/css/client.css">
</head>
<body>
<div class="container">
    <h1>文件夹文件批量重命名工具</h1>

    <div>
        <button id="selectFolderBtn">选择文件夹</button>
        <span id="selectedFolder"></span>
    </div>

    <div id="fileListContainer" style="display: none;">
        <h3>文件夹中的文件:</h3>
        <div id="fileList"></div>

        <div class="rename-options">
            <h3>重命名选项</h3>
            <div>
                <label for="prefix">前缀:</label>
                <input type="text" id="prefix" placeholder="例如: 图片_">
            </div>
            <div>
                <label for="startNumber">起始序号:</label>
                <input type="number" id="startNumber" value="1" min="1">
            </div>
            <div>
                <label for="padding">序号位数:</label>
                <select id="padding">
                    <option value="1">1 (1, 2, 3...)</option>
                    <option value="2">2 (01, 02, 03...)</option>
                    <option value="3" selected>3 (001, 002, 003...)</option>
                    <option value="4">4 (0001, 0002, 0003...)</option>
                </select>
            </div>
            <div>
                <label for="suffix">后缀:</label>
                <input type="text" id="suffix" placeholder="例如: _版本1">
            </div>
            <button id="renameBtn" disabled>开始重命名</button>
        </div>
    </div>

    <div id="status" class="status" style="display: none;"></div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', function () {
        const selectFolderBtn = document.getElementById('selectFolderBtn');
        const selectedFolderSpan = document.getElementById('selectedFolder');
        const fileListContainer = document.getElementById('fileListContainer');
        const fileListDiv = document.getElementById('fileList');
        const renameBtn = document.getElementById('renameBtn');
        const statusDiv = document.getElementById('status');

        let folderHandle;
        let files = [];

        // 选择文件夹
        selectFolderBtn.addEventListener('click', async function () {
            try {
                if (!('showDirectoryPicker' in window)) {
                    return
                }
                // 使用showDirectoryPicker API选择文件夹
                folderHandle = await window.showDirectoryPicker();
                selectedFolderSpan.textContent = `已选择: ${folderHandle.name}`;

                // 读取文件夹中的文件
                files = await readFolderFiles(folderHandle);

                // 显示文件列表
                displayFileList(files);
                fileListContainer.style.display = 'block';
                renameBtn.disabled = false;

                // 清除状态
                statusDiv.style.display = 'none';
            } catch (error) {
                if (error.name !== 'AbortError') {
                    showStatus(`错误: ${error.message}`, 'error');
                }
            }
        });

        // 重命名按钮点击事件
        renameBtn.addEventListener('click', async function () {
            if (!folderHandle || files.length === 0) return;

            const prefix = document.getElementById('prefix').value;
            const startNumber = parseInt(document.getElementById('startNumber').value);
            const padding = parseInt(document.getElementById('padding').value);
            const suffix = document.getElementById('suffix').value;

            try {
                renameBtn.disabled = true;
                renameBtn.textContent = '重命名中...';

                // 执行重命名操作
                const results = await renameFiles(
                    folderHandle,
                    files,
                    prefix,
                    startNumber,
                    padding,
                    suffix
                );

                // 显示结果
                let successCount = results.filter(r => r.success).length;
                if (successCount === files.length) {
                    showStatus(`成功重命名了 ${successCount} 个文件!`, 'success');
                } else {
                    showStatus(`成功重命名了 ${successCount} 个文件，${files.length - successCount} 个失败`, 'error');
                }

                // 刷新文件列表
                files = await readFolderFiles(folderHandle);
                displayFileList(files);
            } catch (error) {
                showStatus(`重命名过程中出错: ${error.message}`, 'error');
            } finally {
                renameBtn.disabled = false;
                renameBtn.textContent = '开始重命名';
            }
        });

        // 读取文件夹中的文件
        async function readFolderFiles(folderHandle) {
            const files = [];

            for await (const entry of folderHandle.values()) {
                if (entry.kind === 'file') {
                    files.push({
                        handle: entry,
                        name: entry.name,
                        oldName: entry.name
                    });
                }
            }

            // 按文件名排序
            files.sort((a, b) => a.name.localeCompare(b.name));

            return files;
        }

        // 显示文件列表
        function displayFileList(files) {
            fileListDiv.innerHTML = '';

            if (files.length === 0) {
                fileListDiv.innerHTML = '<p>文件夹中没有文件</p>';
                return;
            }

            files.forEach(file => {
                const fileItem = document.createElement('div');
                fileItem.className = 'file-item';
                fileItem.innerHTML = `
                        <span>${file.oldName}</span>
                        ${file.oldName !== file.name ? `<span style="color: green;">→ ${file.name}</span>` : ''}
                    `;
                fileListDiv.appendChild(fileItem);
            });
        }

        // 重命名文件
        async function renameFiles(folderHandle, files, prefix, startNumber, padding, suffix) {
            const results = [];
            let counter = startNumber;

            for (const file of files) {
                try {
                    // 获取文件扩展名
                    const ext = file.name.split('.').pop();
                    const nameWithoutExt = file.name.substring(0, file.name.lastIndexOf('.'));

                    // 构建新文件名
                    const paddedNumber = String(counter).padStart(padding, '0');
                    const newName = `${prefix}${paddedNumber}${suffix}.${ext}`;

                    // 重命名文件
                    await file.handle.move(newName);

                    // 更新文件信息
                    file.oldName = file.name;
                    file.name = newName;

                    results.push({success: true, fileName: newName});
                    counter++;
                } catch (error) {
                    results.push({
                        success: false,
                        fileName: file.name,
                        error: error.message
                    });
                }
            }

            return results;
        }

        // 显示状态信息
        function showStatus(message, type) {
            statusDiv.textContent = message;
            statusDiv.className = `status ${type}`;
            statusDiv.style.display = 'block';
        }
    });
</script>
</body>
</html>